package com.summer.study.leetcode.thread.foobar_115;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @auther: 杨杰
 * @date: 2019/7/25 11:31
 * @description:
 */
public class AtomicDemo {

    private int n;

    private AtomicInteger num;

    public AtomicDemo(int n) {
        this.n = n;
        this.num = new AtomicInteger(n * 2);
    }


    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            while (num.get() % 2 == 0) {
            }
            printFoo.run();
            num.getAndDecrement();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            while (num.get() % 2 == 1) {
            }
            printBar.run();
            num.getAndDecrement();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        AtomicDemo demo = new AtomicDemo(10);
        Thread t1 = new Thread(() -> {
            System.out.println("foo");
        });

        Thread t2 = new Thread(() -> {
            System.out.println("bar");
        });

        new Thread(() -> {
            try {
                demo.foo(t1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                demo.bar(t2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }
}
